<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row style="padding-bottom: 30px;">
          <a-col :span="24" v-if="isShow">
            <a-form-model-item label="编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="number">
              <a-input v-model="model.number" placeholder="请输入编号" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="报价名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="name">
              <a-input v-model="model.name" placeholder="请输入报价名称" @blur="formatName"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="客户" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="customerId">
              <JSelectMultiUser v-model="model.customerId" :query-config="selectUserQueryConfig" :url="kehuurl"
                                @change="kehuChange" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="联系人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="contactsIds">
              <lianxiren v-model="model.contactsIds" :query-config="lianxirenConfig" :multiple="false"
                         :url="lianxirenUrl" v-if="customerIdShow" @change="jihuiChange"></lianxiren>
              <span v-else>无</span>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="关联机会" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="opportunityId">
              <xiaoshoujihui displayKey="number" v-model="model.opportunityId" :query-config="jihuiConfig"
                             :multiple="false" :url="xiaoshoujihuiUrl" v-if="customerIdShow"></xiaoshoujihui>
              <span v-else>无</span>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="报价人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bidder">
              <j-select-user-by-dep v-model="model.bidder" :multi="false" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="报价时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bidderTime">
              <j-date placeholder="请选择报价时间" v-model="model.bidderTime" :show-time="true"
                      date-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="有效日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="effectiveDate">
              <j-date placeholder="请选择有效日期" v-model="model.effectiveDate" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="状态" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="state">
              <j-dict-select-tag type="list" v-model="model.state" dictCode="quotation_state" placeholder="请选择状态" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="负责人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="directorIds">
              <j-select-user-by-dep v-model="model.directorIds" :multi="true" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="协同人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="collaboratorIds">
              <j-select-user-by-dep v-model="model.collaboratorIds" :multi="true" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="产品" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="productList">
              <a-button class="editable-add-btn" @click="chanPinAdd">
                添加产品
              </a-button>
              <a-table bordered
                       :dataSource="dataSource"
                       :columns="columns"
                       :pagination="false"
                       :scroll="{x:true}"
                       rowKey="id">

                <template slot="name" slot-scope="text, record">
                  <span>{{ text }}</span>
                </template>
                <template slot="number" slot-scope="text, record">
                  <span>{{ text }}</span>
                </template>
                <!--                规格-->
                <template slot="specifications" slot-scope="text, record,index">
                  <span>{{ text }}</span>
                </template>
                <!--                条码-->
                <template slot="barCode" slot-scope="text, record">
                  <span>{{ text }}</span>
                </template>
                <!--                报价单位-->
                <template slot="unit" slot-scope="text, record">
                  <j-dict-select-tag type="list" v-model="text" dictCode="product_unit" disabled />
                </template>
                <!--                数量-->
                <template slot="num" slot-scope="text, record">
                  <span>{{ text }}</span>
                </template>
                <!--                单价-->
                <template slot="unitPrice" slot-scope="text, record">
                  <span>{{ text }}</span>
                </template>
                <!--                折扣-->
                <template slot="discount" slot-scope="text, record">
                  <span>{{ text }}</span>
                </template>
                <!--                售价-->
                <template slot="quotedPrice" slot-scope="text, record">
                  <span>{{ text }}</span>
                </template>
                <!--                报价小计-->
                <template slot="quotedPriceTotal" slot-scope="text, record">
                  <span>{{ text }}</span>
                </template>
                <!--                备注-->
                <template slot="remarks" slot-scope="text, record">
                  <span>{{ text }}</span>
                </template>
                <template slot="operation" slot-scope="text, record,index">
                  <a @click="contactsEdit(record)">编辑</a>
                  <a-divider type="vertical" />
                  <a @click="contactsDel(index)">删除</a>

                </template>
              </a-table>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="产品合计" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="totalProducts">
              <a-input-number :defaultValue="0" v-model="model.totalProducts" placeholder="请输入产品合计" disabled
                              class="w100"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="整体折扣率" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="discountRate">
              <a-input-number v-model="model.discountRate" placeholder="请输入折扣率" addon-after="%" class="w100"
                              @blur="quotationAmountComputer"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="其他费用" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="otherExpenses">
              <a-input-number v-model="model.otherExpenses" placeholder="请输入其他费用" class="w100"
                              @blur="quotationAmountComputer"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="优惠价钱" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="preferentialAmount">
              <a-input-number v-model="model.preferentialAmount" placeholder="请输入优惠价钱" class="w100"
                              @blur="quotationAmountComputer"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="报价金额" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="quotationAmount"
                               extra="报价金额=产品合计*整单折扣率+其他费用-优惠金额">

              <a-input-number v-model="model.quotationAmount" placeholder="请输入报价金额" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <!--          <a-col :span="24">
                      <a-form-model-item label="归档" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="filed">
                        <j-dict-select-tag type="list" v-model="model.filed" dictCode="is_filed" placeholder="请选择归档" />
                      </a-form-model-item>
                    </a-col>-->
        </a-row>
      </a-form-model>
    </j-form-container>
    <productInfoModal ref="productInfo" @ok="productEditOK"></productInfoModal>
  </a-spin>
</template>

<script>

import { httpAction, getAction } from '@/api/manage'
import JSelectUserByDep from '@/components/jeecgbiz/JSelectUserByDepCustom'
import JSelectMultiUser from '@/components/jeecgbiz/JSelectMultiUserCustom'
import lianxiren from '@/components/jeecgbiz/lianxirenCustom'
import xiaoshoujihui from '@/components/jeecgbiz/xiaoshoujihui/index'
import JSelectUserByDepModalCustom from '@/components/jeecgbiz/modal/JSelectUserByDepModalCustom'
import { validateDuplicateValue } from '@/utils/util'
import LIANXIREN from '@/components/LIANXIREN/index'
import EditableCell from '@/components/EditableCell/cell'
import productInfoModal from '@comp/ProductInfo/ProductInfoModal'

export default {
  name: 'QuotationForm',
  components: {
    JSelectUserByDep,
    JSelectMultiUser,
    JSelectUserByDepModalCustom,
    lianxiren,
    xiaoshoujihui,
    LIANXIREN,
    EditableCell,
    productInfoModal
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  data() {
    return {
      tempProductList: {
        productList: []
      },
      tableShow: true,
      //产品使用
      count: 1,
      dataSource: [],
      columns: [
        {
          title: '产品名称',
          dataIndex: 'name',
          key: 'name',
          width: 200,
          scopedSlots: { customRender: 'name' }
        },
        {
          title: '产品编号',
          dataIndex: 'number',
          width: 200,
          key: 'number',
          scopedSlots: { customRender: 'number' }
        },
        {
          title: '规格',
          dataIndex: 'specifications',
          width: 150,
          key: 'specifications',
          scopedSlots: { customRender: 'specifications' }
        },
        {
          title: '产品条码',
          dataIndex: 'barCode',
          width: 150,
          key: 'barCode',
          scopedSlots: { customRender: 'barCode' }
        },
        {
          title: '报价单位',
          dataIndex: 'unit',
          key: 'unit',
          width: 150,
          scopedSlots: { customRender: 'unit' }
        },
        /* {
          title: '分类',
          dataIndex: 'type',
          key: 'type',
          width: 150,
          scopedSlots: { customRender: 'type' }
        }, */
        {
          title: '数量',
          dataIndex: 'num',
          key: 'num',
          width: 150,
          scopedSlots: { customRender: 'num' }
        },
        {
          title: '单价',
          dataIndex: 'unitPrice',
          key: 'unitPrice',
          width: 150,
          scopedSlots: { customRender: 'unitPrice' }
        },
        {
          title: '折扣(%)',
          dataIndex: 'discount',
          key: 'discount',
          width: 150,
          scopedSlots: { customRender: 'discount' }
        },
        {
          title: '报价',
          dataIndex: 'quotedPrice',
          key: 'quotedPrice',
          width: 150,
          scopedSlots: { customRender: 'quotedPrice' }
        },
        {
          title: '报价小计',
          dataIndex: 'quotedPriceTotal',
          key: 'quotedPriceTotal',
          width: 150,
          scopedSlots: { customRender: 'quotedPriceTotal' }
        },
        {
          title: '备注',
          dataIndex: 'remarks',
          key: 'remarks',
          width: 150,
          scopedSlots: { customRender: 'remarks' }
        },
        {
          title: '操作',
          dataIndex: 'operation',
          key: 'operation',
          width: 150,
          fixed: 'right',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      rules: {
        name: {
          rules: [
            {
              required: true,
              message: '请选择产品'
            }
          ]
        },
        phone: {
          rules: [
            {
              required: true,
              message: '请输入手机号'
            }
            /* {
              validator: (rule, value, callback) =>{
                var reg=/^1[3456789]\d{9}$/
                if(!reg.test(value)){
                  callback(new Error("请输入正确手机号"))
                }else{
                  callback()

                }
              },
              message: '请输入正确手机号',
              trigger: ['change']
            } */
          ]
        }
      },
      customerIdShow: false,
      isShow: false,
      kehuurl: '/customer/customer/lists?filed=2&id=',
      // kehuurl: '',
      // 选择用户查询条件配置
      selectUserQueryConfig: [
        { key: 'phone', label: '电话' }
      ],
      //联系人
      lianxirenUrl: '/sys/common/queryCustomerId?customerId=',
      lianxirenConfig: [
        { key: 'name', label: '姓名' }
        /* {key: 'leixing', label: '类型'},
        {key: 'tel', label: '电话'} */

      ],
      xiaoshoujihuiUrl: '/sys/common/querySalesOpportuninty?customerId=',
      jihuiConfig: [
        { key: 'number', label: '编号' }

      ],
      model: {
        discountRate: 100,
        quotationAmount: 0
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      confirmLoading: false,
      validatorRules: {
        /* number: [
           { required: true, message: '请输入编号!'},
        ], */
        name: [
          { required: true, message: '请输入报价名称!' }
        ],
        customerId: [
          { required: true, message: '请输入客户!' }
        ],
        directorIds: [
          { required: true, message: '请选择负责人' }
        ],
        bidder: [
          { required: true, message: '请输入报价人!' }
        ],
        discountRate: [
          { required: true, message: '请输入整体折扣率!' },
          {
            validator: (rule, value, callback) => {

              if (Number(value) < 1 || Number(value) > 100) {
                callback(false)
              } else {
                callback()

              }
            },
            message: '整单折扣率请控制在1到100之间',
            trigger: ['blur']
          }
        ],
        bidderTime: [
          { required: true, message: '请输入报价时间!' }
        ],
        state: [
          { required: true, message: '请输入状态!' }
        ],
        preferentialAmount: [
          { required: false },
          { pattern: /^(([1-9][0-9]*)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/, message: '请输入正确的金额!' }
        ],
        quotationAmount: [
          { required: true, message: '请输入!' },
          { pattern: /^(([1-9][0-9]*)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/, message: '请输入正确的金额!' }
        ]
      },
      url: {
        add: '/quotation/quotation/add',
        edit: '/quotation/quotation/edit',
        queryById: '/quotation/quotation/queryById'
        //:""//编号生成
      }
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    }
  },
  watch: {
    'model.customerId': {
      deep: true,
      immediate: true,
      handler(newValue, oldValue) {
        console.log('model.customerID变化', newValue)

        if (!newValue || newValue !== oldValue) {
          this.customerIdShow = false
        }
        // console.log('newValue', newValue)
        // console.log('oldValue', oldValue)
        if (newValue) {
          this.$nextTick(() => {
            this.customerIdShow = true
            this.kehuurl = '/customer/customer/lists?filed=2&id=' + newValue
            console.log('执行新的kehuurl', this.kehuurl)
            if (this.model.opportunityId) {
              this.xiaoshoujihuiUrl = '/sales/salesOpportuninty/lists?customerId=' + newValue + '&id=' + this.model.opportunityId
              this.lianxirenUrl = '/sys/common/queryCustomerId?customerId=' + newValue + '&id=' + this.model.contactsIds
            } else {
              this.xiaoshoujihuiUrl = '/sales/salesOpportuninty/lists?customerId=' + newValue
              this.lianxirenUrl = '/sys/common/queryCustomerId?customerId=' + newValue
            }
          })

        }

      }
    }

  },
  created() {
    //备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model))
  },
  methods: {
    formatName() {
      let name = this.model.name
      this.model.name = name.trim()
    },
//报价金额变化
    quotationAmountComputer() {
      //此判断为解决编辑时候空产品导致总价为0的异常
      if (this.dataSource.length <= 0) {
        console.log('无产品')
        this.model.quotationAmount = 0
        return false
      }
      console.log('总价金额变化quotationAmountComputer()')
      this.model.quotationAmount = Number(this.model.totalProducts) * Number(this.model.discountRate) / 100 + (this.model.otherExpenses ? Number(this.model.otherExpenses) : 0) - (this.model.preferentialAmount ? Number(this.model.preferentialAmount) : 0)
    },

    //移除产品列表里的某一条产品
    contactsDel(index) {
      console.log(index)
      this.dataSource.splice(index, 1)
      // this.model.productList = this.dataSource
      //重新计算总价
      this.totalProductsComputer()
      this.quotationAmountComputer('删除以重新计算总价', null)
    },
    //产品编辑
    contactsEdit(record) {
      this.$refs.productInfo.edit(record)
    },
    kehuChange(e) {
      console.log(e)
      this.customerIdShow = false
      this.model.opportunityId = ''
      this.model.contactsIds = ''
      /* this.xiaoshoujihuiUrl = '/sys/common/querySalesOpportuninty?customerId=' + e
      this.lianxirenUrl = '/sys/common/queryCustomerId?customerId=' + e */
    },
    jihuiChange(e) {
      console.log(e)
    },
    add() {
      this.edit(this.modelDefault)
      this.isShow = false
      // this.model.discountRate = 100  //默认折扣率
      this.model.totalProducts = 0  //默认产品合计
    },
    edit(record) {
      console.log('record', record)
      this.isShow = true
      //临存变量
      this.tempProductList = record
      this.model = Object.assign({}, record)
      console.log('合并数据', this.model)
      let count = 0
      console.log('==============record', record)
      if (record.productList.length > 0) {
        record.productList.map(res => {
          res.key = count += 1
          return res
        })
        console.log('编辑初始化产品列表', record.productList)
        this.dataSource = record.productList
      }

      this.visible = true
    },
    submitForm() {
      console.log('this.dataSource', this.dataSource)
      console.log('this.model1111111111111111', this.model)

      this.model.productList = this.dataSource
      console.log('this.model2222222222222222', this.model)
      let obj = Object.assign({}, this.model)
      // debugger
      const that = this
      // 触发表单验证
      this.$refs.form.validate(valid => {
        if (valid) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          console.log('提交前model', obj)
          httpAction(httpurl, obj, method).then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.$emit('ok')
            } else {
              that.$message.warning(res.message)
            }
          }).finally(() => {
            that.confirmLoading = false
          })
        }

      })
    },

    //总价计算
    totalProductsComputer() {
      const ageSum = this.dataSource.reduce((ageSum, e) => {
        return ageSum += Number(e.quotedPriceTotal)
      }, 0)
      this.model.totalProducts = ageSum
      this.quotationAmountComputer()
      // return all
    },

    //添加产品
    chanPinAdd() {
      this.$refs.productInfo.add()
    },

    productEditOK(res) {
      console.log('添加产品返回数据', res)
      const { count, dataSource } = this
      if (res.key) {
        //编辑的情况
        const dataSource = [...this.dataSource]
        let target = dataSource.find((item) => item.key == res.key)
        target = Object.assign(target, res)
        this.dataSource = dataSource
      } else {
        //新增的情况
        let newData = Object.assign(res, { key: count })
        this.dataSource = [...this.dataSource, newData]
        this.count += 1
      }
      this.totalProductsComputer()

    }
  }
}
</script>
<style scoped lang="less">
.w100 {
  width: 100%;
}
</style>